package org.numanint.wizard;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.wst.common.frameworks.datamodel.IDataModel;
import org.eclipse.wst.common.frameworks.internal.operations.IProjectCreationPropertiesNew;
import org.eclipse.wst.web.ui.internal.wizards.SimpleWebProjectFirstPage;
import org.numanint.Activator;
import org.numanint.code.Generator;
import org.numanint.code.GeneratorProperties;
import org.numanint.code.ReverseEngineer;
import org.numanint.utils.UIutils;
import org.osgi.framework.Bundle;

public class MyWebProjectWizard extends org.eclipse.jst.servlet.ui.project.facet.WebProjectWizard  {

	private ProgressMonitorDialog dialog;
	public static IProject project; 
	public MyWebProjectWizard(IDataModel model) {
		super(model);	
	}
	
	public MyWebProjectWizard() {
		super();
		setNeedsProgressMonitor(true);
		setWindowTitle("Numanint-新建一个Web框架");
	}

	@SuppressWarnings("restriction")
	protected IDataModel createDataModel() {		
		IDataModel dataModel = super.createDataModel();
		dataModel.setProperty(IProjectCreationPropertiesNew.PROJECT_NAME, "BlankFramework");
		return dataModel;
	}
	
	@Override
	protected IWizardPage[] createBeginingPages() {
		SimpleWebProjectFirstPage creationPage =  new SimpleWebProjectFirstPage(this.model, "first.page");
		creationPage.setTitle("Numanint-新建一个Web框架");
		creationPage.setDescription("创建一个Web框架,基于spring 2.5.x和hibernate3.x");
		creationPage.setImageDescriptor(UIutils.getImageDescriptor("/icons/numanint-48.png"));
		return new IWizardPage[] {
				new WebProjectWizardTwo(),new WebProjectWizardThree(),	createFirstPage()
		};
	}
	
	
	public boolean performFinish (){
		super.performFinish();
		saveWebProjectConfig();// 保存工程参数
		IRunnableWithProgress runnable = new IRunnableWithProgress (){
			public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
				try{		
					monitor.beginTask("Start...",1000);
					monitor.worked(10);
					Thread.sleep(50);
					unzipBlankFramework();// 解压空工程
					monitor.setTaskName("解压空工程...");
					monitor.worked(30);
					Thread.sleep(500);
					updateBlankFramework();//更新空工程
					monitor.setTaskName("更新空工程...");
					monitor.worked(40);					
					Thread.sleep(500);
					generatorBlankFramwork();//生成工程基础pojo，dao，xml
					monitor.setTaskName("生成工程基础pojo,dao,bo,controller,xml...");
					monitor.worked(90);
					Thread.sleep(500);
					project.refreshLocal(IResource.DEPTH_INFINITE, null);
					monitor.setTaskName("刷新建立的工程...");
					monitor.worked(100);
					Thread.sleep(500);
					monitor.done();
				}catch(Exception e){
					//MessageDialog.openError(getShell(),"错误信息",e.getMessage()); 
					e.printStackTrace();
				}
			}
		};
		
		dialog = new ProgressMonitorDialog(getShell());
			try {
			dialog.run(true,true,runnable);
			} catch (InvocationTargetException e) {			
			e.printStackTrace();
			} catch (InterruptedException e) {			
			e.printStackTrace();
			}
		return true;
	}

	public void saveWebProjectConfig() {
		WebProjectConfig.projectName = model.getStringProperty("IProjectCreationPropertiesNew.PROJECT_NAME");
		String location = "";
		if(model.getBooleanProperty("IProjectCreationPropertiesNew.USE_DEFAULT_LOCATION"))
			location = model.getStringProperty("IProjectCreationPropertiesNew.DEFAULT_LOCATION");
		else 
			location = model.getStringProperty("IProjectCreationPropertiesNew.USER_DEFINED_LOCATION");
		WebProjectConfig.projectWorkspacePath = location+ System.getProperty("file.separator");
		project = (IProject) getDataModel().getProperty("IProjectCreationPropertiesNew.PROJECT");
		FacetDataModelMap map = (FacetDataModelMap) model.getProperty("IFacetProjectCreationDataModelProperties.FACET_DM_MAP");
		IDataModel webModel = (IDataModel) map.get("jst.web");
//		Iterator it = webModel.getAllProperties().iterator();
//		while(it.hasNext()){
//			String s = (String)it.next();
//			System.out.println(s+"="+webModel.getProperty(s));
//		}
		WebProjectConfig.srcDir = (String)webModel.getProperty("IWebFacetInstallDataModelProperties.SOURCE_FOLDER");
		WebProjectConfig.webContent = (String)webModel.getProperty("IJ2EEFacetInstallDataModelProperties.CONFIG_FOLDER");
		WebProjectConfig.contextRoot = (String)webModel.getProperty("IWebFacetInstallDataModelProperties.CONTEXT_ROOT");
	}

	private void unzipBlankFramework() throws Exception {
		Bundle bundle = Platform.getBundle(Activator.PLUGIN_ID);
		InputStream is = FileLocator.toFileURL(bundle.getEntry("resources/"+WebProjectConfig.blankFrameworkName+".zip")).openStream();
		UIutils.unjar(is, WebProjectConfig.projectWorkspacePath);
	}

	private void updateBlankFramework() throws Exception{
		String webInfPath = WebProjectConfig.projectWorkspacePath + System.getProperty("file.separator")+
		WebProjectConfig.webContent + System.getProperty("file.separator")+
		"WEB-INF"+ System.getProperty("file.separator");
		UIutils.txtFileReplace(webInfPath+"web.xml",  WebProjectConfig.blankFrameworkName, WebProjectConfig.projectName);
		UIutils.txtFileReplace(webInfPath+"applicationContext.xml"
				, "<!--<property name=\"configLocation\" value=\"classpath:org/xwlabs/pojo/hibernate.cfg.xml\"/>-->"
				, "<property name=\"configLocation\" value=\"classpath:"+WebProjectConfig.pojoPkgName.replace('.','/')+"/hibernate.cfg.xml\"/>");
		String propertiesPath =webInfPath+"properties"+System.getProperty("file.separator");
		UIutils.txtFileReplace(propertiesPath+"log4j.properties", WebProjectConfig.blankFrameworkName, WebProjectConfig.projectName);
		UIutils.txtFileReplace(propertiesPath+"jdbc.properties", "jdbc.driverClassName=", "jdbc.driverClassName="+WebProjectConfig.projectDBConfig.driver+System.getProperty("line.separator")+"#");
		UIutils.txtFileReplace(propertiesPath+"jdbc.properties", "jdbc.url=", "jdbc.url="+WebProjectConfig.projectDBConfig.url+System.getProperty("line.separator")+"#");
		UIutils.txtFileReplace(propertiesPath+"jdbc.properties", "jdbc.username=", "jdbc.username="+WebProjectConfig.projectDBConfig.username+System.getProperty("line.separator")+"#");
		UIutils.txtFileReplace(propertiesPath+"jdbc.properties", "jdbc.password=", "jdbc.password="+WebProjectConfig.projectDBConfig.password+System.getProperty("line.separator")+"#");
	}
	
	private void generatorBlankFramwork() throws Exception{		
		GeneratorProperties properties = new GeneratorProperties();
		properties.setProjectName(WebProjectConfig.projectName);
		properties.setProjectDir(WebProjectConfig.projectWorkspacePath);
		properties.setSampleName("sample");
		properties.setSrcDir(WebProjectConfig.srcDir);
		properties.setWebRoot(WebProjectConfig.contextRoot);
		properties.setWebContent(WebProjectConfig.webContent);
		properties.setPojoPkgName(WebProjectConfig.pojoPkgName);
		properties.setDaoPkgName(WebProjectConfig.daoPkgName);
		properties.setBoPkgName(WebProjectConfig.boPkgName);
		properties.setControllerPkgName(WebProjectConfig.controllerPkgName);	
		properties.setValidatorPkgName(WebProjectConfig.validatorPkgName);
		ReverseEngineer reveng = new ReverseEngineer(WebProjectConfig.conn,WebProjectConfig.projectModelTableNames,WebProjectConfig.selectedSchema);
		reveng.reverse(	);
		Generator generator = new Generator(properties);
		generator.generatorAll(reveng);		
	}
	

}